package org.sam.swing.renderer;

import java.awt.Component;
import java.io.File;

import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JList;
import javax.swing.SwingConstants;

/**
 * list控件的带有图片绘制功能的renderer对象
 * 
 * @author sam
 *
 */
public class ImageListCellRender extends DefaultListCellRenderer {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8625482686373691458L;

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Component getListCellRendererComponent(JList<? extends Object> list, Object value, int index,
			boolean isSelected, boolean cellHasFocus) {
		if (value instanceof File) {
			File imageFile = (File) value;
			try {
				ImageIcon icon = new ImageIcon(imageFile.toURI().toURL());
				setIcon(icon);
				setText(imageFile.getName());
				setVerticalTextPosition(SwingConstants.CENTER);
				setHorizontalTextPosition(SwingConstants.RIGHT);

				if (isSelected) {
					this.setBackground(list.getSelectionBackground());
				} else {
					this.setBackground(list.getBackground());
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return this;
	}

}
